import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Card, Pagination, Form, Row, Col,Avatar,Popover,Modal,Table,Spin,
    Select, Input, InputNumber, DatePicker,Button, Icon, Tabs, List,message,Tooltip
} from 'antd';
import styles from './index.less';
import moment from 'moment';
import CancelOrder from './cancelOrder';
import ChangePrice from './changePrice';
import ChangeRemark from './changeRemark';
import ExportOrder from './exportOrder';
import ReportForm from './reportForm';
import {abs} from '@/utils/utils';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const TabPane = Tabs.TabPane;
const confirm = Modal.confirm;

const orderStatus = [
    {
        label: '全部',
        value: 0
    },
    {
      label: '待付款',
      value: 1
  },
  {
      label: '待发货',
      value: 2
  },
  {
      label: '已发货',
      value: 3
  },
  {
      label: '退款中',
      value: 4
  },
  {
      label: '已完成',
      value: 5
  },
  {
      label: '已关闭',
      value: 6
  },
]

@Form.create()
class CardList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        formValues: {},
        formData: {},
        navOrderState: '0',
        visible: false,
        Sort: 'Desc',
        clickScreen: false,
        paginationProps: {
          showSizeChanger: true,
          showQuickJumper: false,
          showTotal: total => `共 ${total} 条记录`,
          pageSize: 10,
          total: 0,
          pageIndex: 1,
        },
        loadFinished: false,
        btnLoading: false,
        serchLoading: false,
        exportLoading: false,
    };
  }
  componentWillMount(){
    this.getOrderList();
    window.Isoption = false;
  }

  componentDidMount() {
    window.Isoption = true;
  }

  getOrderList = params => {
    const { dispatch} = this.props;
    const { paginationProps: { pageIndex, pageSize }, Sort } = this.state;
    dispatch({
        type: 'orderList/GetOrderList',
        payload: {
            PageIndex: pageIndex, //页码
            PageSize: pageSize, //页数
            ProductWord: params && params.ProductWord ? params.ProductWord : '', //商品
            MemberWord: params && params.MemberWord ? params.MemberWord : '', //客户
            OrderNo: params && params.OrderNo ? params.OrderNo : '', //单号
            MinDate: params && params.MinDate? params.MinDate: null,
            MaxDate: params && params.MaxDate? params.MaxDate: null,
            RightsStatus: params && params.RightsStatus? params.RightsStatus: 0, //维权状态
            PaymentChannel: params && params.PaymentChannel? params.PaymentChannel: 0, //支付方式
            DeliveryType: params && params.DeliveryType? params.DeliveryType: 0, //	配送方式
            OrderStatus: params && params.OrderStatus? params.OrderStatus: 0, //订单状态
            Sort: Sort,
        },
        callBack: {
            success: res => {
                if(res.Code ===0) {
                  this.setState({
                    paginationProps: {
                        ...this.state.paginationProps,
                        total: res.Data.Total
                    },
                    dataSource: res.Data,
                    loadFinished: true,
                    btnLoading: false,
                    serchLoading: false,
                  })
                }
            },
            error: res => {
                console.log(res)
            }
        }
    })
  }

  // 重置
  handleFormReset =() => {
    const { form } = this.props;
    form.resetFields();
    this.setState({
        navOrderState: '0'
    })
  }

  // 筛选
  handleSearch = e => {
    e.preventDefault();
    this.setState({
        btnLoading: true,
        serchLoading: true
    })
    const { form } = this.props;
    form.validateFields((err, values) => {
        if(err) return;
        const datas = {
            ...values,
            MaxDate:values.Date && values.Date[1]?moment(values.Date[1]).format('YYYY-MM-DD'):'',
            MinDate:values.Date && values.Date[0]?moment(values.Date[0]).format('YYYY-MM-DD'):'',
        };
        this.setState({
            formValues: datas,
            navOrderState: values.OrderStatus.toString()
        })
       this.getOrderList({...datas});
    })
  }

  // 点击导航
  changeTabs = (key) => {
     const {formValues} = this.state;
      this.props.form.setFieldsValue({
        OrderStatus: key/1
      });
    formValues.OrderStatus=key/1;
    this.setState({
        formValues,
        serchLoading: true,
        navOrderState: key.toString() // 导航状态
    })
    this.getOrderList({...formValues});
  }

  // 收货方法
  requestFinishOrder =(orderNo) => {
    const { dispatch} = this.props;
    const  {formValues} = this.state;
    dispatch({
        type: 'orderList/SetFinishOrder',
        payload: {
          OrderNo: orderNo
        },
        callBack: {
            success: res=> {
                if(res.Code ===0) {
                  message.success('确认成功');
                  this.getOrderList({...formValues});
                }
            },
            error: res =>{
              message.success(res.Msg);
            }
        },
    })
  }

  // 确认收货
  clickSetFinishOrder =(orderNo) => {
    const that = this;
    confirm({
        title: '确认所选择的的订单已经收货吗?',
        content: '收货后,所选择的订单将变为完成状态!',
        okText: '确认',
        cancelText: '取消',
        onOk() {
            that.requestFinishOrder(orderNo)
        },
      });
}

  // 刷新页面
  clickrefrech = () => {
    const {formValues} = this.state;
    this.getOrderList({...formValues});
}

// 时间排序
onTabChange =(pagination, filters, sorter) => {
    const {formValues, navOrderState, formData} = this.state;
    if(sorter.order ==='descend') {
        formData.Sort ='Desc';
        this.setState({
            Sort: 'Desc'
        })
    } else {
        formData.Sort ='Asc';
        this.setState({
            Sort: 'Asc'
        })
    }
    formValues.OrderStatus= navOrderState;
    this.setState({
        formValues,
        formData,
        serchLoading: true
    })
    this.getOrderList({...formValues});
}

  // 点击单个分页
  onChangeOnePage = (current, pageSize) => {
    let { paginationProps, navOrderState, formValues} = this.state;
    let pagination = {
      ...paginationProps,
      pageIndex: current,
      pageSize: pageSize
    };
    formValues.OrderStatus= navOrderState;
    this.setState({
      paginationProps: pagination,
      formValues,
      serchLoading: true
    }, () => {
      this.getOrderList({...formValues});
    })
  }

  // 改变显示长度
  onShowSizeChange =(current, pageSize) => {
    let { paginationProps, navOrderState, formValues} = this.state;
    let pagination = {
      ...paginationProps,
      pageIndex: current,
      pageSize: pageSize
    };
    formValues.OrderStatus= navOrderState;
    this.setState({
      paginationProps: pagination,
      formValues,
      serchLoading: true
    }, () => {
      this.getOrderList({...formValues});
    })
  }


// 点击导出
clickexportOrder =() => {
  const { dispatch, form} = this.props;
    form.validateFields((err, values) => {
        if(values.Date) {
            // let a = moment(values.Date[1]).format('YYYY,MM,DD');
            // let b = moment(values.Date[0]).format('YYYY,MM,DD');
            // console.log(a, b)
            // let time =  moment([`${a}`]).diff(moment([`${b}`]),'days');
            // console.log(time);
            const datas = {
                ...values,
                MaxDate:values.Date && values.Date[1]?moment(values.Date[1]).format('YYYY-MM-DD'):'',
                MinDate:values.Date && values.Date[0]?moment(values.Date[0]).format('YYYY-MM-DD'):'',
            };
            this.setState({
              formData: datas,
              exportLoading: true,
          })
            dispatch({
              type: 'orderList/GetTaskName',
              payload: {
                  TaskType: 0
              },
              callBack: {
                  success: res => {
                      if(res.Code===0) {
                          this.setState({
                              data: res.Data,
                              visible: true,
                              exportLoading: false
                          })
                      }
                  },
                  error: res=> {
                      message.error(res.Msg)
                  }
              }
          })
        } else {
            message.error('请选择起始时间')
        }
    })
}

// 点击查看
clickReportForm =() => {
    const title="已生成报表";
    const TaskType = 0; //类型
    const width = 640;
    this.reportForm.show({width, title, TaskType})
}

// 点击详情
clickDetail =(OrderNo) => {
    window.open(`/#/${window.storeId}/order/details/${OrderNo}`);
}

  renderForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    const {btnLoading, exportLoading} = this.state;
    return (
        <Form onSubmit={this.handleSearch} layout="inline" className={styles.formItems}>
        <Row>
          <Col span={8}>
            <FormItem label="商品信息">
              {getFieldDecorator('ProductWord')(
                <Input placeholder="商品名称/商品编码"  style={{ width: '100%' }}/>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="买家信息">
              {getFieldDecorator('MemberWord')(
                <Input placeholder="昵称/手机号"  style={{ width: '100%' }}/>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="订单号">
              {getFieldDecorator('OrderNo')(
                <Input placeholder="订单号"  style={{ width: '100%' }}/>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label="下单时间">
              {getFieldDecorator('Date')(<RangePicker style={{ width: '100%' }} placeholder={['开始日期', '    结束日期']} />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="维权状态">
                {getFieldDecorator('RightsStatus', {initialValue: 0})(
                    <Select placeholder="请选择" className="xkd-width-per-100">
                        <Option value={0}>全部</Option>
                        <Option value={1}>退款处理中</Option>
                        <Option value={2}>退款结束</Option>
                    </Select>
                    )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="支付方式">
                {getFieldDecorator('PaymentChannel', {initialValue: 0})(
                    <Select placeholder="请选择" className="xkd-width-per-100">
                        <Option value={0}>全部</Option>
                        <Option value={1}>微信支付</Option>
                        <Option value={2}>货到付款</Option>
                        <Option value={3}>线下支付</Option>
                        <Option value={4}>到店付款</Option>
                    </Select>
                )}
            </FormItem>
            </Col>
        </Row>
        <Row>
            <Col span={8}>
                <FormItem label="订单状态">
                {getFieldDecorator('OrderStatus',{initialValue: 0})(
                    <Select placeholder="请选择" style={{ width: '100%' }}>
                        {orderStatus.map((item, index) => (
                            <Option value={item.value} key={index}>{item.label}</Option>
                        ))}
                    </Select>
                )}
                </FormItem>
            </Col>
            <Col span={8}>
                <FormItem label="配送方式">
                    {getFieldDecorator('DeliveryType', {initialValue: 0})(
                        <Select placeholder="请选择" style={{ width: '100%' }}>
                            <Option value={0}>全部</Option>
                            <Option value={1}>快递发货</Option>
                            <Option value={3}>同城配送</Option>
                            <Option value={2}>上门自提</Option>
                        </Select>
                    )}
                </FormItem>
            </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div className="screenNavButton">
                <Button type="primary" htmlType="submit" loading={btnLoading}>
                    筛选
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                    重置
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={() =>this.clickexportOrder()} loading={exportLoading}>
                    订单导出
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.clickReportForm}>
                    查看已生成报表
                </Button>
            </div>
        </div>
      </Form>
    )
  }

  render() {
      const { paginationProps, dataSource, loadFinished, formData, navOrderState, serchLoading} = this.state;
      const {oemInfo} = this.props;
      const columns =[
        {
          title: '商品信息',
          dataIndex: 'NickName',
          width:'20.8%'
        },
        {
          title: '单价/数量',
          dataIndex: 'Telephone',
          width:'12.5%',
          align: 'right',
        },
        {
          title: '售后',
          dataIndex: 'LastBuyTime',
          width:'8.3%'
        },
        {
          title: '买家信息',
          dataIndex: 'TotalPoints',
          width:'12.5%'
        },
        {
          title: '订单状态',
          dataIndex: 'TotalFee',
          width:'8.3%'
        },
        {
          title: '下单时间',
          dataIndex: 'TotalFeeNum',
          width:'11.6%',
          sorter: (a, b) =>moment(a.ShowDateTime).valueOf() - moment(b.ShowDateTime).valueOf(),
        },
        {
          title: '实付金额',
          dataIndex: 'SingleFee',
          width:'17%',
          align: 'right',
        },
        {
          title: '操作',
          align: 'right',
        },
      ];
    return (
        <Fragment>
            <Spin spinning={!loadFinished}>
            <Card bordered={false} className={styles.contentBox}>
              <div style={{height:206,background:'#fafafa',marginBottom:16,paddingTop:16,paddingRight:16,boxSizing:'border-box'}}>
                <div className="tableListForm">{this.renderForm()}</div>
              </div>

            <div>
            </div>
            <Tabs onChange={this.changeTabs} type="card" activeKey={navOrderState} className={styles.bodyContent}>
                {orderStatus.map(item => {
                    return (
                        <TabPane tab={item.label} key={item.value}>
                            <div className="tooltipRoot">
                                <List
                                    header={
                                        <Table
                                            dataSource={null}
                                            columns={columns}
                                            onChange={this.onTabChange}
                                        />
                                    }
                                    loading={serchLoading}
                                    itemLayout="vertical"
                                    size="large"
                                    dataSource={dataSource&& dataSource.DataList?dataSource.DataList:[]}
                                    renderItem={vel => {
                                        const iamgeVel  = vel.OrderTag ===0 ?6: vel.OrderTag
                                        return (
                                            <List.Item className={styles.listBody}>
                                                <Row className={styles.navtebalRow}>
                                                    <Col span={18} className={styles.orderNo}>
                                                        <span>订单号: {vel.OrderNo}</span>
                                                        <span>
                                                          <span>{vel.DeliveryTypeName}</span>
                                                          <span style={{marginLeft: 2, marginRight: 2}}>/</span>
                                                          <span>{vel.PaymentChannelNameStr}</span>
                                                        </span>
                                                    </Col>
                                                    <Col span={6}>
                                                        <div className={styles.rightTagImage}>
                                                        {vel.Remark && (
                                                              <Popover title="买家留言" content={vel.Remark}>
                                                              <span className={styles.span1}>
                                                                  <img
                                                                      src={oemInfo&&oemInfo.cdnUrl?oemInfo['cdnUrl'] + '/' + 'xkdnewyun/systemfile/store/icon/orderlist-wx.png' +'?x-oss-process=style/240':''}
                                                                      width={16}
                                                                      height={16}
                                                                  />
                                                              </span>
                                                          </Popover>
                                                        )}
                                                            <span className={styles.span2} onClick={
                                                                () => {
                                                                    const title="修改备注";
                                                                    const OrderNo = vel.OrderNo;
                                                                    this.changeRemark.show({title, OrderNo}, this.clickrefrech)
                                                                }
                                                            }>
                                                            {vel.MerchantRemark?(
                                                                <Tooltip title={vel.MerchantRemark} getPopupContainer={() => document.querySelector(`.tooltipRoot`)} >
                                                                    <img
                                                                        src={oemInfo&&oemInfo.cdnUrl?oemInfo['cdnUrl'] + '/' + `xkdnewyun/systemfile/store/icon/orderlist-remark0${iamgeVel}.png` +'?x-oss-process=style/240':''}
                                                                        width={16}
                                                                        height={16}
                                                                    />
                                                                </Tooltip>
                                                            ):(
                                                                <img
                                                                    src={oemInfo&&oemInfo.cdnUrl?oemInfo['cdnUrl'] + '/' + `xkdnewyun/systemfile/store/icon/orderlist-remark0${iamgeVel}.png` +'?x-oss-process=style/240':''}
                                                                    width={16}
                                                                    height={16}
                                                                />
                                                            )}
                                                            </span>
                                                        </div>
                                                    </Col>
                                                </Row>
                                                <Row className={styles.navRowItem} style={{height: `${vel.OrderItem.length * 96}px`}}>
                                                    <Col span={10}>
                                                        <List
                                                            dataSource={vel.OrderItem ?vel.OrderItem:[]}
                                                            renderItem={(data, index) => {
                                                                return (
                                                                    <Row className={vel.OrderItem.length === index+ 1 ?styles.leftItemNoborder : styles.leftItem}>
                                                                        <Col span={19}>
                                                                            <List.Item key={data.Id} className={styles.listItem}>
                                                                                <List.Item.Meta
                                                                                    avatar={<Avatar src={oemInfo&&oemInfo.cdnUrl?oemInfo['cdnUrl'] + '/' + data.ThumbnailUrl +'?x-oss-process=style/240':''} />}
                                                                                    title={
                                                                                        <span title={data.ProductName} style={{maxWidth:145,height:40}}>
                                                                                            {data.ProductName}
                                                                                        </span>
                                                                                    }
                                                                                    description={
                                                                                        <span
                                                                                            title={data.SkuName}
                                                                                            className="xkd-text-ellipsis"
                                                                                        >{data.SkuName}</span>
                                                                                    }
                                                                                />
                                                                                   <div>
                                                                                        <div>{'￥' +abs(data.SingleFee,2)}</div>
                                                                                        <div>{'x'+ data.BuyNum}</div>
                                                                                    </div>
                                                                            </List.Item>
                                                                        </Col>
                                                                        <Col span={5}>{data.RightsStatusName}</Col>
                                                                    </Row>
                                                                )
                                                            }}
                                                        >
                                                        </List>
                                                    </Col>
                                                    <Col span={3}>
                                                    <div>
                                                        {vel.MemberRemark && <div>{'['+vel.MemberRemark+']'}</div>}
                                                        <div>{vel.MemberName}</div>
                                                        <div>{vel.MemberTelephone}</div>
                                                    </div>
                                                    </Col>
                                                    <Col span={2}>
                                                        {vel.OrderStatusName}
                                                    </Col>
                                                    <Col span={3}>{vel.CreateTime}</Col>
                                                    <Col span={4} style={{textAlign: 'right'}}>
                                                        <div>
                                                            <div>￥{abs(vel.OrderFee,2)}</div>
                                                            <div className={styles.dollor}>{'('+'含运费'+'￥'+ abs(vel.FreightFee,2) +')'}</div>
                                                            {vel.OrderStatus===1&&<div><a onClick={
                                                                  () => {
                                                                    const title=`订单原价(含运费)：￥${abs(vel.OrderFee,2)}`;
                                                                    const OrderNo = vel.OrderNo;
                                                                    const width =960;
                                                                    this.changePrice.show({width,title,OrderNo}, this.clickrefrech)
                                                                }
                                                            }>修改价格</a></div>}
                                                        </div>
                                                    </Col>
                                                    <Col span={2} style={{textAlign: 'right'}}>
                                                        {vel.OrderStatus===2 &&(vel.PaymentChannelNameStr==='货到付款' ||vel.PaymentChannelNameStr==='到店付款')&&
                                                        <Button type="primary" size="small" style={{marginBottom:8}} onClick={()=> {
                                                                const title="取消订单";
                                                                const OrderNo = vel.OrderNo;
                                                                const width =320;
                                                                this.cancelOrder.show({width,title,OrderNo}, this.clickrefrech)
                                                            }}
                                                        >
                                                            取消订单
                                                        </Button>}
                                                        {vel.OrderStatus===1&&
                                                        <Button type="primary" size="small" style={{marginBottom:8}} onClick={()=> {
                                                                const title="取消订单";
                                                                const OrderNo = vel.OrderNo;
                                                                const width =320;
                                                                this.cancelOrder.show({width,title,OrderNo}, this.clickrefrech)
                                                            }}
                                                        >
                                                            取消订单
                                                        </Button>}
                                                        {/* {vel.OrderStatus===3&&
                                                        <Button type="primary" size="small" style={{marginBottom:8}} onClick={() =>this.clickSetFinishOrder(vel.OrderNo)}>确认收货</Button>} */}
                                                        <Button size="small" onClick={() => this.clickDetail(vel.OrderNo)}>查看详情</Button>
                                                    </Col>
                                                </Row>
                                            </List.Item>
                                        )
                                    }}
                                >
                                </List>
                                <Pagination
                                    showSizeChanger
                                    onChange={this.onChangeOnePage}
                                    onShowSizeChange={this.onShowSizeChange}
                                    showTotal={paginationProps.showTotal}
                                    total={paginationProps.total}
                                    current={paginationProps.pageIndex}
                                    pageSize={paginationProps.pageSize}
                                    style={{textAlign: 'right'}}
                                />
                            </div>
                        </TabPane>
                    )
                })}
            </Tabs>
            </Card>
            </Spin>
            <CancelOrder
                ref ={e => {
                    this.cancelOrder = e;
                }}
            />
            <ChangePrice
                ref ={e => {
                    this.changePrice = e;
                }}
            />
            <ChangeRemark
                ref ={e => {
                    this.changeRemark = e;
                }}
            />
            <ExportOrder _this = {this} visible={this.state.visible} data={formData} TaskType={0}/>

            <ReportForm
                ref={e => {
                    this.reportForm = e;
                }}
            />
        </Fragment>
    );
  }
}


export default connect(({ orderList,global, loading }) => ({
    orderList,
    oemInfo: global.oemInfo,
    // loading1: loading.effects['orderList/GetOrderList'],
  }))(CardList)
